//
//  MRMixtureRatioDetailController.m
//  ERP
//
//  Created by QA on 15/11/26.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MRMixtureRatioDetailController.h"
#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"
#import "Charts-Swift.h"
#import "KWFormViewQuickBuilder.h"
#import "NSMutableDictionary+Format.h"

#import "GEProgressBarTableViewCell.h"
#import "GEObjectValueTableViewCell.h"
#import "StringAxisValueFormatter.h"

@interface MRMixtureRatioDetailController ()

@property (nonatomic,strong) NSDictionary *contractBaseInfo;
@property (nonatomic,strong) NSMutableArray *contractData;

@end

@implementation MRMixtureRatioDetailController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"施工配合比明细"];
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    NSDictionary *dic = object;
    self.contractBaseInfo = dic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //绘制图表数据
    GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
    if (progressBarCell == nil) {
        NSString *identifierBar = [NSString stringWithFormat:@"MCGEProgressBarTableViewCell%ld",(long)indexPath.section];
        progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
        progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
    }
    
    //判读有无数据，有数据就加载页面
    if(progressBarCell.objectValue){
        NSString *identifier = [NSString stringWithFormat:@"MCGEObjectValueTableViewCell%ld",(long)indexPath.section];
        GEObjectValueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.objectValue = progressBarCell.objectValue;
            //添加图表
            if(indexPath.section == 0){ //实验与实际配合比分析
                [self compareMixtureRatioChartInCell:cell indexPath:indexPath];
            } else if(indexPath.section == 1){ //施工配合比详情
                KWFormView *formView = [self reloadTableCell:cell indexPath:indexPath];
                [cell.contentView addSubview:formView];
            }
        }
        return cell;
    }
    
    //绘制进度条,并加载数据
    NSString *number = [self.contractBaseInfo objectFormatStringForKey:@"配合比编号"];
    NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
    [mDictionary setFormatObject:number forKey:@"配合比编号" defaults:@""];
    if (indexPath.section == 0) { //实验与实际配合比分析
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"SYZJ_SGPB_REPORT_20151203" parameter:mDictionary index:indexPath.section];
    } else if (indexPath.section == 1) { //施工配合比详情
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"SYZJ_SGPB_REPORT_20151203" parameter:mDictionary index:indexPath.section];
    }
    return progressBarCell;
}


- (void)compareMixtureRatioChartInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"配合比实际与设定误差率(%)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    UIButton *subLable = [[UIButton alloc] initWithFrame:CGRectMake(20, 26, SuperWidth - 40, 32)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:subLable];
    subLable.userInteractionEnabled = YES;
    
    NSString *showString = [NSString stringWithFormat:@"明细请参照配比详情 下表"];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [subLable setAttributedTitle:lableText forState:UIControlStateNormal];
    
    BarChartView *_chartView = [[BarChartView alloc] initWithFrame:CGRectMake(0, 46, SuperWidth, 240)];
//    _chartView.descriptionText = @"";
//    _chartView.noDataTextDescription = @"暂无数据";
    
    _chartView.drawBarShadowEnabled = NO;
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawGridBackgroundEnabled = NO;
    
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawLabelsEnabled = YES;
    
    ChartYAxis *leftAxis = _chartView.leftAxis;
    leftAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;
    leftAxis.spaceTop = 0.15;
    
    ChartYAxis *rightAxis = _chartView.rightAxis;
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    rightAxis.spaceTop = 0.15;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;
    l.verticalAlignment = ChartLegendVerticalAlignmentBottom;
    l.orientation = ChartLegendOrientationHorizontal;
    l.form = ChartLegendFormSquare;
    l.formSize = 9.0;
    l.font = [UIFont systemFontOfSize:11.f];
    l.xEntrySpace = 4.0;
    
    [self setMixtureRatioChartDataChart:_chartView data:valueArray];
    [cell.contentView addSubview:_chartView];
    [_chartView animateWithXAxisDuration:2.0 yAxisDuration:2.0];
}

- (void)setMixtureRatioChartDataChart:(BarChartView *)chartView data:(NSArray*)array
{
    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    NSMutableArray *entries = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *mDictionary = [array objectAtIndex:i];
        NSString *name = [mDictionary objectFormatStringForKey:@"材料名称规格" defaults:@"未知"];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"差值比(%)"];
        
        [xVals addObject:name];
        [entries addObject:[[BarChartDataEntry alloc] initWithX:i y:value]];
    }
    
    //设置底部显示文字
    chartView.xAxis.granularity = 1.0; // only intervals 
    chartView.xAxis.valueFormatter = [[StringAxisValueFormatter alloc] initWithData:xVals];
    
    NSNumberFormatter *leftAxisFormatter = [[NSNumberFormatter alloc] init];
    leftAxisFormatter.minimumFractionDigits = 0;
    leftAxisFormatter.maximumFractionDigits = 1;
    leftAxisFormatter.negativeSuffix = @"%";
    leftAxisFormatter.positiveSuffix = @"%";
    
    BarChartDataSet *set = [[BarChartDataSet alloc] initWithValues:entries label:@"实际与设定差值比(%)"];
    //set.drawIconsEnabled = NO;
    set.stackLabels = xVals;
    [set setColor:[UIColor colorWithRed:240/255.f green:120/255.f blue:124/255.f alpha:1.f]];
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set];
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:leftAxisFormatter]];
    [data setDrawValues:YES];
    data.barWidth = 0.5f;
    
    chartView.data = data;
}

//配合比详情页面设置
- (KWFormView *)reloadTableCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    NSArray *titles = @[@"材料名称规格",@"配比用量(kg)",@"施工用量(kg)",@"砂浆用量(kg)",@"误差值(kg)"];
    
    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    [builder setBorderColor:[UIColor colorWithWhite:0.88 alpha:1.0]];
    [builder addRecord:titles];
    
    for(int i = 0 ;i < valueArray.count; i++){
        NSDictionary *mDictionary = [valueArray objectAtIndex:i];
        NSString *clggmc = [mDictionary objectFormatStringForKey:@"材料名称规格" defaults:@"未知"];
        NSString *sdyl = [mDictionary objectFormatStringForKey:@"设定用量(kg)" defaults:@"未知"];
        NSString *sjyl = [mDictionary objectFormatStringForKey:@"实际用量(kg)" defaults:@"未知"];
        NSString *sjjyl = [mDictionary objectFormatStringForKey:@"砂浆用量(kg)" defaults:@"未知"];
        
        CGFloat sj = [mDictionary objectFormatFloatForKey:@"实际用量(kg)" retain:1 except:1];
        CGFloat sd = [mDictionary objectFormatFloatForKey:@"设定用量(kg)" retain:1 except:1];
        NSString *czb = [NSString stringWithFormat:@"%0.2f",sj - sd];
        [builder addRecord:@[clggmc,sdyl,sjyl,sjjyl,czb]];
    }
    
    CGFloat itemWidth = SuperWidth/7.9;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*1.9)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value4 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value5 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    
    KWFormView *formView = [builder startCreatWithWidths:@[value1,value2,value3,value4,value5] startPoint:CGPointMake(0, 0)];
    formView.mKWFormViewHeight = 30;
    return formView;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"实际与设定配合比分析";
    } else if(section == 1){
        lable.text = @"施工配合比详情";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 290;
    } else if(indexPath.section == 1){
        GEObjectValueTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (!cell.objectValue) return 240;
        KWFormView *formView = [self reloadTableCell:cell indexPath:indexPath];
        return [formView getFormViewHeight] + 1;
    }
    
    GEProgressBarTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
    if(!(cell && cell.objectValue)) return 240;
    
    NSArray *valueArray = [cell.objectValue firstObject];
    if (valueArray.count <= 0) return 240;
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

@end
